﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using DevComponents.DotNetBar.Controls;
using System.Data;

namespace BUL
{
    public partial class Business
    {      
        public void GetAllChatLieu(string strTimkiem, DataGridViewX dataGridViewX )
        {
            if(dataGridViewX.RowCount>0)
                dataGridViewX.Rows.Clear();
            using (var dal = new QuanLyBanHangEntities1())
            {
                var listResult = dal.tblChatLieux.Where(x => x.TenChatLieu.Contains(strTimkiem)).OrderBy(x => x.TenChatLieu);
                int i = 0;
                foreach (var item in listResult)
                {
                    dataGridViewX.Rows.Add();
                    dataGridViewX.Rows[i].Cells[0].Value = "N";
                    dataGridViewX.Rows[i].Cells[1].Value = item.MaChatLieu;
                    dataGridViewX.Rows[i].Cells[2].Value = item.TenChatLieu;
                    dataGridViewX.Rows[i].Cells[3].Value = item.GhiChu;
                    i++;
                }
            }
        }

        public tblChatLieu GetChatLieuById(string machatlieu)
        {
            return _dal.tblChatLieux.Where(x => x.MaChatLieu == machatlieu).FirstOrDefault();
        }

        public void InsertChatLieu(tblChatLieu chatlieu)
        {
            _dal.tblChatLieux.AddObject(chatlieu);
            _dal.SaveChanges();
        }

        public void UpdateChatLieu(string maChatLieuCu,tblChatLieu chatlieu)
        {
            // dal.tblBoPhans.Where(x => x.MaBP == maBoPhanCu) : lấy ra toàn bộ các bản ghi thỏa mãn where
            //FirstOrDefault() lấy ra bản ghi đầu tiên trong danh sách thỏa mãn where, nếu không có kết quả sẽ là null
            var CLUpdate = _dal.tblChatLieux.Where(x => x.MaChatLieu == maChatLieuCu).FirstOrDefault();
            CLUpdate.MaChatLieu = chatlieu.MaChatLieu;
            CLUpdate.TenChatLieu = chatlieu.TenChatLieu;
            CLUpdate.GhiChu = chatlieu.GhiChu;
            _dal.SaveChanges();
        }

        public void DeleteCL(IEnumerable<string> machatlieus)
        {
            var listDelete = _dal.tblChatLieux.Where(x => machatlieus.Contains(x.MaChatLieu));
            foreach (var tblchatlieu in listDelete)
            {
                _dal.tblChatLieux.DeleteObject(tblchatlieu);
            }
            _dal.SaveChanges();
        }

        public tblChatLieu BuildCL(string maCL, string tenCL, string ghichu)
        {
            return new tblChatLieu { MaChatLieu = maCL, TenChatLieu = tenCL, GhiChu = ghichu };
        }
    }
}
